package com.ww.springboot.boot.thread.study.base.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo2 {


    int count = 0;
    Lock lock = new ReentrantLock();
    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();
    Condition conditionC = lock.newCondition();

    public void printA() {
        while (count < 50) {
            //加锁
            lock.lock();
            try {
                // 打印A
                System.out.println("A");
                count ++;
                // 唤醒打印B的线程
                conditionB.signal();
                // 将自己放入ConditionA的容器中，等待其他线程的唤醒
                conditionA.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 释放锁
                lock.unlock();
            }
        }


    }

    public void printB() {
        while (count < 50) {
            // 加锁
            lock.lock();
            try {
                // 打印B
                System.out.println("B");
                count ++;
                // 唤醒打印C的线程
                conditionC.signal();
                // 将自己放入ConditionB的容器中，等待其他线程的唤醒
                conditionB.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 释放锁
                lock.unlock();
            }
        }
    }


    public void printC() {
        while (count < 50) {
            // 加锁
            lock.lock();
            try {
                // 打印B
                System.out.println("C");
                count ++;
                // 唤醒打印A的线程
                conditionA.signal();
                // 将自己放入ConditionC的容器中，等待其他线程的唤醒
                conditionC.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        LockDemo2 test = new LockDemo2();
        // 建立打印ABC的三个线程
        Thread theadA = new Thread(() -> {
            test.printA();
        });
        Thread theadB = new Thread(() -> {
            test.printB();
        });
        Thread theadC = new Thread(() -> {
            test.printC();
        });
    
        // 启动线程
        theadA.start();
        theadB.start();
        theadC.start();

    }
}